<?php

namespace extend;

class FieldSet
{

    /**
     * 字符串分割成可选参数
     * @auth false
     * @param $params
     * @return array
     */
    static function split($params)
    {
        $arr = array_filter(preg_split("/[(\|)(\r\n)]/", $params['option_value']));

        $result = [];

        if ($arr) {
            foreach ($arr as $index => $str) {
                $tmp = preg_split("/[:-]/", $str); 
                if (isset($tmp[1])) {
                    $result[  $tmp[0]  ] = $tmp[1];
                } else {
                    $result[  $index  ] = $tmp[0];
                }
            }
        }

        return $result;
    }

    /**
     * JSON配置转换为参数
     * @auth false
     * @param $params
     * @return array|mixed
     */
    static function json($params)
    {
        $result = [];

        if ($params['option_value']) {
            $result = @ json_decode($params['option_value'], true);
        }
        return $result;
    }

    /**
     * 连表获取数据用于radio select 选项
     * @auth false
     * @param $params
     * @return array|mixed
     */
    static function table($params)
    {

        if (!in_array($params['type'], ['radio', 'select', 'checkbox'])) {
            return $params['option_value'];
        }

        $list = [];

        if ($params['option_value']) {

            @list($re_table, $fields, $show_field, $search_fields, $pk, $where) = explode('|', $params['option_value']);

            if (!$pk) {
                return [];
            }

            $fields = array_filter(explode(',', $fields));
            $show_field = array_filter(explode(',', $show_field));

            $fields = array_filter(array_merge($fields, $show_field));
            $DB = db();
            $where && $DB->where($where);

            $data = $DB->get($re_table, 10, $fields);

            if ($data) {
                foreach ($data as $row) {
                    $title = '';
                    foreach ($show_field as $f) {
                        $title .= '【' . $row[$f] . '】';
                    }
                    $list[$row[$pk]] = $title;
                }
            }
        }

        return $list;
    }


    static function tree($params){

        if(!$params['option_value']){
            return [];
        }

        @list($table,$fields,$id,$pid,$show,$where)=explode('|',$params['option_value']);

        if(!isset($show) || !$show){
            return [];
        }

        $DB=db();

        if($where){
            $DB->where($where);
        }

        $data=$DB->get($table,null,$fields);


        $tree=Tree::toFormatTree($data,$show,$id,$pid);

        $result=[];
        if($tree){
            foreach ($tree as $row){
                $result[$row[$id]]=$row['title'];
            }
        }
         return $result;
    }
}